# -*- coding: utf-8 -*-
import pendulum
from datetime import timedelta
from time import time
from utils.operators.rich_sql_sensor import RichSqlSensor
from airflow.exceptions import AirflowSkipException


cst = pendulum.timezone('Asia/Shanghai')

class PieceRichSqlSensor(RichSqlSensor):

    def pre_execute(self, context):
        day = cst.convert(context['ti'].execution_date) + timedelta(days=1)

        schedule_date = ['01']

        if day.strftime('%d') not in schedule_date:
            print(f'{day.strftime("%d")} not in {schedule_date}, should skip')
            raise AirflowSkipException()
        else:
            print(f'{day.strftime("%d")} in {schedule_date}, run now')
            super().pre_execute(context)

#doris表名
doris_table = "dm_piece_weight_segment_month_summary"
#hive中表名
hive_table = "dm_piece_weight_segment_month_summary"
#Task ID
task_id = f"doris_{doris_table}"

label = f"doris_{doris_table}_{int(time())}"
timeout = timedelta(minutes=60).seconds


doris_dm_piece_weight_segment_month_summary = PieceRichSqlSensor(
    task_id=f'doris_dm_piece_weight_segment_month_summary',
    pool='broker_load_pool',
    email=['jarl.huang@jtexpress.com','yl_bigdata@yl-scm.com'],
    conn_id='new_doris',
    pre_sql=f"""
    TRUNCATE TABLE spmi_dm.{doris_table} PARTITION (p{{{{ execution_date | date_add(1) | add_month(-1) | cst_month_nodash }}}});
    LOAD LABEL spmi_dm.{label} (
        DATA INFILE(
                    "hdfs://{{{{var.value.hadoop_namespace}}}}/dw/hive/spmi_dm.db/external/{hive_table}/mt={{{{ execution_date | date_add(1) | add_month(-1) | cst_month_dash }}}}/*"
                    )
        INTO TABLE {doris_table}  
    FORMAT AS 'PARQUET'
    )
    WITH BROKER '{{{{ var.json.doris_brokers | random_choice }}}}'
    PROPERTIES ('timeout'='{timeout}', 'max_filter_ratio'='0.0')""",
    poke_sql=f"SHOW LOAD FROM spmi_dm WHERE label = '{label}' ORDER BY CreateTime DESC LIMIT 1",
    sql_on_kill=f"CANCEL LOAD FROM spmi_dm WHERE LABEL = '{label}'",
    success=lambda r: r[2] == 'FINISHED',
    failure=lambda r: (r[2] is not None and r[2] == 'CANCELLED', str(r[7])),
    poke_interval=60,
    execution_timeout=timedelta(seconds=timeout + 120), )

doris_dm_piece_weight_segment_month_summary